<template>
    <view class="nova-column">
        <image class="banner" src="../../static/jn/jn_head.png"></image>
        <view class="nova-column" style="padding: 30rpx;">
            <view class="nova-column publish" v-if="job">
                <view class="border-bottom nova-row-center">
                    <text class="job">{{ job.title }}</text>
                    <text style="color: #666; font-size: 24rpx;">请选择您需要的服务技能</text>
                </view>
                <block v-if="job && job.items && job.items.length > 0">
                    <view v-for="(item, index) in job.items" :key="index" class="nova-column">
                        <text class="title" v-if="item.type != 'date'">{{ item.title }}</text>
                        <!--                    <nova-grid
                        v-if="item.type === 'radio' || item.type === 'checkbox'"
                        class="grid"
                        :column="3"
                        :hspace="40"
                        :vspace="30"
                        :ratio="0"
                        :choiceMode="item.type === 'radio' ? 1 : -1"
                        :checkedIndices="item.checkedIndices"
                        :highlight="false"
                        :name="item.key"
                        @change="change"
                    >
                        <nova-grid-item v-for="(sub, idx) in item.options" :key="idx" :itemIndex="idx">
                            <view class="option" :class="{ checked: item.value.split(',').indexOf(sub) >= 0 }">{{ sub }}</view>
                        </nova-grid-item>
                    </nova-grid> -->
                        <view
                            v-if="item.type === 'radio' || item.type === 'checkbox'"
                            class="grid"
                            :data-name="item.key"
                            :data-choiceMode="item.type === 'radio' ? 1 : -1"
                            :data-mutextIndex="item.custom ? item.options.length - 1 : -1"
                            :data-checkedIndices="item.checkedIndices"
                            :ref="item.key"
                        >
                            <block v-for="(sub, idx) in item.options" :key="idx" :itemIndex="idx">
                                <view
                                    class="option"
                                    :class="{ checked: item.checkedIndices.indexOf(idx) >= 0 }"
                                    :data-name="item.key"
                                    :data-index="index"
                                    :data-index2="idx"
                                    @click="change2"
                                    :style="{ marginRight: idx % 3 == 2 ? '0' : '40rpx' }"
                                >
                                    {{ sub }}
                                </view>
                            </block>
                            <view
                                class="nova-row-center"
                                style="height: 60rpx; min-width: 180rpx; box-sizing: border-box;"
                                v-if="item.custom"
                                :style="{ display: getOtherDisplay(item) }"
                            >
                                <view class="nova-row-center grid" v-if="item.customtype == 'range'">
                                    <input class="option" v-model="item.min" :data-i="index" type="number" />
                                    <text style="padding: 0 20rpx;">-</text>
                                    <input class="option" v-model="item.max" :data-i="index" type="number" />
                                </view>
                                <block v-else>
                                    <input class="custom-input" :type="item.customtype" :placeholder="item.placeholder" v-model="item.value" />
                                    <text v-if="item.customunit" class="unit">{{ item.customunit }}</text>
                                </block>
                            </view>
                        </view>
                        <view v-if="item.type === 'text'" class="nova-row-center grid">
                            <input class="option" :placeholder="item.placeholder" v-model="item.value" />
                            <block></block>
                        </view>
                        <view v-if="item.type === 'range'" class="nova-row-center grid">
                            <input class="option range-option" v-model="item.min" :data-i="index" :type="item.inputType || 'number'" />
                            <text style="padding: 0 20rpx;">-</text>
                            <input class="option range-option" v-model="item.max" :data-i="index" :type="item.inputType || 'number'" />
                            <text v-if="item.customunit">{{ item.customunit }}</text>
                        </view>
                        <block v-if="item.type === 'date'">
                            <nova-pref
                                class="li-pref"
                                :title="item.title"
                                placeholder="请选择"
                                type="picker"
                                pickerMode="date"
                                :value="item.value"
                                :name="item.key"
                                :data-name="item.key"
                                :data-index="index"
                                @change="changePicker"
                                :arrow="true"
                            ></nova-pref>
                        </block>
                    </view>
                </block>
                <text class="title">关于{{ job.title }}人员还有什么备注要求</text>
                <textarea class="ta" :placeholder="job.tips" v-model="form.tip"></textarea>
            </view>
            <view class="nova-column publish" v-if="job" style="margin-top: 36rpx;">
                <nova-pref
                    class="li-pref"
                    :title="role == 2 ? '我们如何称呼您' : '业主姓名'"
                    placeholder="请输入真实姓名"
                    :arrow="true"
                    name="userName"
                    :value="form.userName"
                    type="input"
                    inputType="text"
                    @input="input"
                ></nova-pref>
                <nova-pref class="li-pref" :title="role == 2 ? '您的性别' : '业主性别'" placeholder="请选择性别" :arrow="true">
                    <radio-group @change="changeSex">
                        <label>
                            <radio value="女" class="" :checked="form.sex == '女'"></radio>
                            女
                        </label>
                        <label>
                            <radio value="男" :checked="form.sex == '男'"></radio>
                            男
                        </label>
                    </radio-group>
                </nova-pref>
                <nova-pref
                    class="li-pref"
                    :title="role == 2 ? '您的年龄' : '业主年龄'"
                    placeholder="请输入"
                    :arrow="true"
                    name="age"
                    :value="form.age"
                    type="input"
                    inputType="number"
                    @input="input"
                ></nova-pref>
                <!--                <nova-pref class="li-pref" title="业主籍贯" placeholder="" :arrow="true">
                    <picker class="picker" mode="selector" :value="places.indexOf(form.place)" @change="changeJG" :range="places">
                        <text v-if="form.place">{{ form.place }}</text>
                        <text v-else class="placeholder">请选择您的籍贯</text>
                    </picker>
                </nova-pref> -->
                <nova-pref
                    class="li-pref"
                    :title="role == 2 ? '您的联系方式' : '业主联系方式'"
                    placeholder="请填写联系方式"
                    :arrow="true"
                    name="userPhone"
                    type="input"
                    inputType="number"
                    :value="form.userPhone"
                    @input="input"
                ></nova-pref>
                <!-- <nova-pref class="li-pref" title="所在小区" placeholder="请选择所在小区" :value="form.village" :arrow="true" @click.native="goMap"></nova-pref> -->
                <nova-pref
                    class="li-pref"
                    :title="role == 2 ? '您所在的区域' : '业主所在区域'"
                    placeholder="请选择所在区域"
                    type="picker"
                    :pickerRange="areas"
                    pickerRangeKey="name"
                    :value="areaIndex"
                    @change="changeArea"
                    :arrow="true"
                ></nova-pref>
                <choose-location class="li-pref" :title="role == 2 ? '您所在的小区' : '业主所在的小区'" placeholder="请选择所在小区" :loc="loc" @change="goMap" />
                <nova-pref class="li-pref last" :title="role == 2 ? '您的心理价位' : '月工资待遇'" placeholder="">
                    <view class="nova-row-center">
                        <view class="" style="flex: 1;"></view>
                        <input class="money" type="number" v-model="form.userWagesLow" />
                        <text style="padding: 8rpx; color: #999999;">-</text>
                        <input class="money" type="number" v-model="form.userWagesHigh" />
                    </view>
                </nova-pref>
            </view>
            <button class="btn-primary" style="margin: 60rpx;" @click="doSubmit">提交</button>
        </view>
        <uni-popup ref="popup" type="center" class="popup">
            <view class="nova-column nova-flex-center content">
                <text style="font-size: 36rpx; margin-top: 110rpx;">需求发布成功</text>
                <text style="font-size: 24rpx; color: #999999; margin-top: 40rpx;">(有效期一个月)</text>
                <view class="nova-row-center" style="margin-top: 110rpx;">
                    <view class="nova-flex nova-flex-center btn" style="background-color: #808080; border-radius: 0 0 0 24rpx;" @click="goBack">取消</view>
                    <view class="nova-flex nova-flex-center btn" style="border-radius: 0 0 24rpx 0;" @click="goBack">确定</view>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import types from '../../common/publish-config.js';
import NovaGrid from '../../components/nova/grid.vue';
import NovaGridItem from '../../components/nova/grid-item.vue';
import NovaPref from '../../components/nova/pref.vue';
import conf from '../../common/conf.js';
import uniPopup from '../../components/uni-popup/uni-popup.vue';
import ChooseLocation from './choose-location.vue';

export default {
    components: {
        NovaGrid,
        NovaGridItem,
        NovaPref,
        ChooseLocation,
        uniPopup
    },
    data() {
        return {
            role: 0,
            index: 0,
            job: undefined,
            areas: [],
            areaIndex: -1,
            info: {},
            places: conf.provinces2,
            form: {
                area: '',
                publish_id: '',
                userWagesHigh: '',
                userPhone: '',
                sex: '',
                type: 2,
                userName: '',
                serviceContent: '',
                tip: '',
                place: '',
                state: 0,
                village: '',
                userWagesLow: '',
                age: ''
            },
            loc: {
                latitude: '',
                longitude: '',
                name: '',
                address: '',
                areaid: ''
            }
        };
    },
    created() {
        this.role = this.$global.role;
    },
    methods: {
        change(e) {
            const name = e.target.name;
            let c = this.job.items.find(function(ele) {
                if (ele.key === name) {
                    return ele;
                }
            });
            let arr = [];
            c.options.forEach((item, index) => {
                if (e.detail.choices.indexOf(index) >= 0) {
                    arr.push(item);
                }
            });
            //c.values = e.detail.choices;
            c.value = arr.join(',');
        },
        getOtherDisplay(item) {
            let last = item.checkedIndices && item.checkedIndices.length > 0 && item.checkedIndices[0] == item.options.length - 1;
            return last ? 'inline-flex' : 'none';
        },
        change2(e) {
            let celld = e.currentTarget.dataset;
            let index = parseInt(celld.index);
            let item = this.job.items[index];
            let i = parseInt(celld.index2);
            let choiceMode = item.type === 'radio' ? 1 : -1;
            let mutexIndex = item.custom ? item.options.length - 1 : -1;
            let checkedIndices = item.checkedIndices || [];
            let has = checkedIndices.indexOf(i);
            if (choiceMode == 1) {
                checkedIndices = [i];
                item.value = item.options[i];
            } else {
                if (has >= 0) {
                    checkedIndices.splice(has, 1);
                } else {
                    // mutex
                    if (mutexIndex >= 0) {
                        if (i === mutexIndex) {
                            checkedIndices = [];
                        } else {
                            let pos = checkedIndices.indexOf(mutexIndex);
                            if (pos >= 0) {
                                checkedIndices.splice(pos, 1);
                            }
                        }
                    }
                    checkedIndices.push(i);
                }
            }
            if (mutexIndex >= 0 && checkedIndices.length == 1 && checkedIndices[0] == mutexIndex) {
                console.log('use cumstom');
                if (item.customtype == 'range') {
                    item.value = item.min && item.max ? `${item.min}-${item.max}` : '';
                } else {
                    item.value = '';
                }
                console.log('use cumstom: ', item.value);
            } else {
                let arr = [];
                item.options.forEach((item2, index2) => {
                    if (checkedIndices.indexOf(index2) >= 0) {
                        arr.push(item2);
                    }
                });
                item.value = arr.join(',');
                console.log('checked: ', item.value);
            }
            item.checkedIndices = checkedIndices;
        },
        changeJG(e) {
            this.form.place = this.places[e.detail.value];
        },
        changeSex(e) {
            this.form.sex = e.detail.value;
            console.log(this.form.sex);
        },
        changeArea(e) {
            this.areaIndex = e.detail.value;
            this.form.area = this.areas[this.areaIndex].name;
        },
        changePicker(e) {
            console.log('pick', e);
            let k = e.target.name;
            let c = this.job.items.find(function(ele) {
                if (ele.key === k) {
                    return ele;
                }
            });
            c.value = e.detail.value;
        },
        input(e) {
            let k = e.target.name;
            this.form[k] = e.detail.value;
        },
        goMap(res) {
            let _this = this;
            _this.form.village = res.name;
            _this.loc = {
                latitude: res.latitude,
                longitude: res.longitude,
                name: res.name,
                address: res.address
            };
            this.form.latitude = res.latitude;
            this.form.longitude = res.longitude;
        },
        async loadData() {
            if (this.form.publish_id) {
                let res = await this.$request.post({
                    url: '/publish/publishEcho',
                    data: {
                        publish_id: this.form.publish_id
                    }
                });
                this.form = res;
                if (res.latitude) {
                    this.loc.latitude = res.latitude;
                }
                if (res.longitude) {
                    this.loc.longitude = res.longitude;
                }
                if (res.village) {
                    this.loc.name = res.village;
                }
                let temp = JSON.parse(this.form.serviceContent).section[0];
                temp.items.forEach(item => {
                    if (item.type === 'range') {
                        let range = item.value ? item.value.split('-') : [0, 0];
                        item.min = range[0];
                        item.max = range[1];
                    } else if (item.type === 'checkbox' || item.type === 'radio') {
                        item.checkedIndices = [];
                        if (item.options.length > 0) {
                            if (item.custom /*|| item.options[item.options.length - 1].indexOf('其他') >= 0*/) {
                                item.custom = true;
                                item.mutexIndex = item.options.length - 1;
                            } else {
                                item.custom = false;
                                item.mutexIndex = -1;
                            }
                        }
                        if (item.checkedIndices === undefined) {
                            item.checkedIndices = [];
                        }
                        if (item.value) {
                            let tmpvs = item.value.split(',');
                            if (tmpvs.length == 0 && item.options.indexOf(item.value) < 0) {
                                if (item.customtype === 'range') {
                                    let range = item.value.split('-');
                                    item.min = range[0];
                                    item.max = range[1];
                                } else {
                                }
                                item.checkedIndices = [item.options.length - 1];
                            } else {
                                tmpvs.forEach(temv => {
                                    item.checkedIndices.push(item.options.indexOf(temv));
                                });
                            }
                        }
                        console.log(item.checkedIndices);
                    }
                });
                if (this.areas) {
                    for (let i = 0; i < this.areas.length; i++) {
                        if (this.areas[i].name === this.form.area) {
                            this.areaIndex = i;
                            break;
                        }
                    }
                }
                this.job = temp;
                console.log('job', this.job);
            } else {
                let res = await this.$request.post({
                    url: '/readJson/readEightJson',
                    skipInterceptorResponse: true,
                    business: undefined
                });
                console.log(res);
                if (res && res.section) {
                    let job = res.section[this.index];
                    job.items.forEach(item => {
                        if (item.options.length > 0) {
                            if (item.custom /* || item.options[item.options.length - 1].indexOf('其他') >= 0*/) {
                                item.custom = true;
                                item.mutexIndex = item.options.length - 1;
                            } else {
                                item.custom = false;
                                item.mutexIndex = -1;
                            }
                        }
                        if (item.checkedIndices === undefined) {
                            item.checkedIndices = [];
                        }
                    });
                    this.job = job;
                    console.log(this.job);
                }
            }
        },
        async doSubmit() {
            let err = '';
            for (let i = 0; i < this.job.items.length; i++) {
                const item = this.job.items[i];
                if (item.type === 'range') {
                    item.value = `${item.min}-${item.max}`;
                    console.log(`${item.title} = ${item.value}`);
                } else if (item.type === 'checkbox' || item.type === 'radio') {
                    if (item.mutexIndex >= 0 && item.checkedIndices.length == 1 && item.checkedIndices[0] == item.mutexIndex) {
                        // other

                        console.log(`${item.title} = ${item.value}`);
                        if (item.min && item.max) {
                        } else {
                        }
                        if (!item.value) {
                            err = item.title;
                            break;
                        }
                    } else {
                        console.log(`${item.title} = ${item.value}`);
                    }
                }
                if (item.require === undefined || item.require) {
                    if (!item.value) {
                        err = item.title;
                        break;
                    }
                }
            }
            console.log(this.job);
            if (!err) {
                if (!this.form.userName) {
                    err = this.role == 2 ? '如何称呼您' : '请输入业主姓名';
                } else if (!this.form.userPhone) {
                    err = '请输入业主联系方式';
                } else if (!this.$isMobile(this.form.userPhone)) {
                    err = '联系方式不是一个有效的手机号码';
                } else if (!this.form.area) {
                    err = '请选择所在区域'
                } else if (!this.form.userWagesLow || !this.form.userWagesHigh) {
                    err = '请输入' + (this.role == 2 ? '您的心理价位' : '月工资待遇');
                } else if (parseInt(this.form.userWagesLow) > parseInt(this.form.userWagesHigh)) {
                    err = (this.role == 2 ? '您的心理价位' : '月工资待遇') + '范围不正确';
                }
            }
            if (err) {
                this.$toast(err);
                return;
            }
            this.form.serviceContent = JSON.stringify({
                section: [this.job]
            });
            if (this.mutex) {
                return;
            }
            this.mutex = true;
            try {
                let res = await this.$request.post({
                    url: '/publish/publishSave',
                    data: this.form,
                    loadingTip: '请稍候...'
                });
                this.$refs.popup.open();
            } catch (err) {
                this.$toast(err.msg || '发布失败');
                this.mutex = false;
            }
        },
        goBack() {
            this.$refs.popup.close();
            // #ifndef H5
            uni.navigateBack();
            // #endif
        },
        async loadUserBasic() {
            let res = await this.$request.post({
                url: '/user/userbasic',
                data: {
                    openid: this.$global.openid,
                    type: this.$global.role
                }
            });

            if (this.$global.role == 2) {
                for (let k in res) {
                    if (this.form.hasOwnProperty(k) && res[k]) {
                        this.form[k] = res[k];
                    }
                }
                if (res.latitude) {
                    this.loc.latitude = res.latitude;
                }
                if (res.longitude) {
                    this.loc.longitude = res.longitude;
                }
                if (res.village) {
                    this.loc.name = res.village;
                }
                if (res.name) {
                    this.form.userName = res.name;
                }
                if (res.phone) {
                    this.form.userPhone = res.phone;
                }
            } else if (this.$global.role == 3) {
                if (res.phone) {
                    this.form.userPhone = res.phone;
                }
            }
        }
    },
    onLoad(options) {
        console.log(options);
        this.areas = this.$global.districts || [];
        this.form.publish_id = options.publish_id || '';
        let i = options.index;
        // #ifdef H5
        if (i === undefined) {
            i = 0;
        }
        if (!this.form.publish_id) {
            this.form.tip = '测试测试';
            this.form.place = '北京';
            this.form.sex = '男';
            this.form.village = '北京东路63号';
            this.form.userName = '李' + Math.ceil(Math.random() * 100000).toString();
            this.form.age = Math.ceil(Math.random() * 100).toString();
            this.form.userPhone = '13912345678';
            this.form.userWagesLow = '3000';
            this.form.userWagesHigh = 3000 + Math.ceil(Math.random() * 1000);
        }
        // #endif
        if (i !== undefined) {
            this.index = parseInt(i);
            this.form.type = this.index + 1;
        }
        this.loadData();
        this.loadUserBasic();
    }
};
</script>

<style lang="scss" scoped>
.page {
    width: 100%;
    background-color: #fcfcfc;
}

.banner {
    width: 100%;
    height: 400rpx;
}

.publish {
    background-color: white;
    border-radius: 10rpx;
    border: 1px solid #f2f2f2;
    box-shadow: 0 0 2rpx #f1f1f1;
    padding: 0 32rpx;

    .border-bottom {
        border-color: #f2f2f2;
        border-style: solid;
        border-width: 0;
        @include thin-border(bottom);
    }

    .job {
        line-height: 95rpx;
        color: $uni-color-primary;
        padding-right: 50rpx;
        font-size: 34rpx;
    }

    .title {
        font-size: 30rpx;
        color: #333333;
        //line-height: 95rpx;
        //min-height: 96rpx;
        padding-top: 32rpx;
        padding-bottom: 32rpx;
    }

    .ta {
        border: 1px solid #ccc;
        border-radius: 10rpx;
        padding: 20rpx 34rpx;
        width: auto;
        height: 180rpx;
        margin-bottom: 60rpx;
    }

    /deep/ .pref-box {
        padding: 0;
        height: 96rpx;
        margin-top: 0rpx;
        &:after {
            @include divider();
        }
    }

    .last /deep/ .pref-box {
        &::after {
            display: none !important;
        }
    }

    .grid {
        flex-wrap: wrap;
        //width: 620rpx;
        .option {
            width: 180rpx;
            height: 60rpx;
            color: #777;
            font-size: 30rpx;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 10rpx;
            //@include thin-border(none);
            border-width: 1rpx;
            border-color: #999;
            border-style: solid;
            padding-left: 4rpx;
            padding-right: 4rpx;
            margin-right: 40rpx;
            margin-bottom: 30rpx;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: hidden;
        }

        .range-option {
            margin-right: 0;
        }

        input.option {
            width: 180rpx;
            padding-left: 20rpx;
        }

        .checked {
            border: none;
            background-color: $uni-color-primary;
            color: white;
        }
        .custom-input {
            padding: 0 24rpx;
            height: 60rpx;
            line-height: 60rpx;
            border-radius: 4rpx;
            border-style: solid;
            border-color: #999999;
            border-width: 1rpx;
            color: #333333;
            font-size: 30rpx;
            width: 120rpx;
        }
    }
    .money {
        padding: 0 24rpx;
        height: 45rpx;
        line-height: 45rpx;
        border-radius: 4rpx;
        border-style: solid;
        border-color: #999999;
        border-width: 1rpx;
        //@include thin-border(none);
        color: #333333;
        font-size: 30rpx;
        width: 120rpx;
    }
}
.popup {
    .content {
        position: relative;
        width: 600rpx;
        border-radius: 24rpx;
        background-color: white;
        .btn {
            width: 300rpx;
            height: 118rpx;
            font-size: 36rpx;
            color: white;
            background-color: $uni-color-primary;
        }
    }
}
</style>
